package china.lzy.service.impl;

import china.lzy.dao.AuthMapper;
import china.lzy.dao.UserMapper;
import china.lzy.entity.ResCode;
import china.lzy.entity.ResResult;
import china.lzy.entity.dto.PageDto;
import china.lzy.entity.pojo.Auth;
import china.lzy.entity.pojo.User;
import china.lzy.exception.AuthErrException;
import china.lzy.exception.ParamErrorException;
import china.lzy.service.UserService;
import china.lzy.utils.AppJwtUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.SecureUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author ：lzy
 * @ Date       ：Created in 14:40 2021/8/10
 * @ Description：
 */

@Service
@Log4j2
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userDao;

    @Autowired
    AuthMapper authDao;
    @Autowired
    RedisTemplate redisTemplate;

    @Override
    @Transactional
    public ResResult saveUser(User user) {
        if (StringUtils.isBlank(user.getPassword()) || StringUtils.isBlank(user.getUsername())) {
            throw new ParamErrorException("用户名或者密码参数错误!");
        }
        //将密码Md5加密
        user.setPassword(SecureUtil.md5(user.getPassword()));
        try {
            int save = userDao.save(user);
            log.info("保存用户:" + save);
            //处理权限
            if (save == 1) {
                boolean B = authDao.insertAuth(new Auth(user.getId(), user.getAuth()));
                if (B) {
                    return ResResult.ResResultBuilder(ResCode.SAVE_OK);
                } else {
                    throw new AuthErrException("权限添加失败");
                }
            } else {
                throw new ParamErrorException("账号创建失败!");
            }
        } catch (Exception e) {
            throw new ParamErrorException("账号或者邮箱存在!");
        }
    }

    @Override
    public ResResult login(User user) {
        if (StringUtils.isBlank(user.getPassword()) || StringUtils.isBlank(user.getUsername())) {
            throw new ParamErrorException("用户名或者密码参数错误!");
        }
        try {
            user.setPassword(SecureUtil.md5(user.getPassword()));
            User loginUser = userDao.login(user);
            if (ObjectUtil.isNotNull(loginUser)) {
                //将Token存储到Redis
                String token = AppJwtUtil.getToken(loginUser);
                log.info(loginUser + "TOKEN" + token);
                redisTemplate.opsForValue().set("TOKEN_USERID_" + loginUser.getId(), token, 1, TimeUnit.DAYS);
                Map map = new HashMap<String, String>();
                map.put("token", token);
                loginUser.setPassword(null);
                map.put("user", loginUser);
                return ResResult.ResResultBuilder(map, ResCode.LOGIN_OK);
            } else {
                return ResResult.ResResultBuilder(ResCode.LOGIN_FAIL);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new ParamErrorException("参数错误");
        }
    }

    @Override
    public ResResult updateUser(User user) {
        if (user.getId() == 0 && StringUtils.isBlank(user.getUsername())) {
            return ResResult.ResResultBuilder(ResCode.OPERATE_ERROR, "参数有问题");
        }
        if (StringUtils.isNotBlank(user.getPassword())) {
            user.setPassword(SecureUtil.md5(user.getPassword()));
        }
        boolean update = userDao.update(user);
        if (update) {
            return ResResult.ResResultBuilder(ResCode.OPERATE_OK);
        } else {
            return ResResult.ResResultBuilder(ResCode.OPERATE_ERROR);
        }
    }

    @Override
    public ResResult delete(User user) {
        if (user.getId() == 0 && StringUtils.isBlank(user.getUsername())) {
            return ResResult.ResResultBuilder(ResCode.OPERATE_ERROR, "参数有问题");
        }
        boolean delete = userDao.delete(user);
        if (delete) {
            return ResResult.ResResultBuilder(ResCode.OPERATE_OK);
        } else {
            return ResResult.ResResultBuilder(ResCode.OPERATE_ERROR);
        }
    }

    @Override
    public ResResult findByPage(PageDto pageDto) {
        if (pageDto.getPageNum() == 0) {
            pageDto.setPageNum(1);
        }
        if (pageDto.getPageSize() == 0) {
            pageDto.setPageSize(10);
        }
        //开启查询
        PageHelper.startPage(pageDto.getPageNum(), pageDto.getPageSize());
        List<User> users = userDao.selectAll();
        PageInfo<User> info = new PageInfo<>(users);
        pageDto.setRecords(users);
        pageDto.setTotal(Integer.valueOf((int) info.getTotal()) );
        return ResResult.ResResultBuilder(pageDto,ResCode.OPERATE_OK);
    }
}
